package adnroid.asynchronous.demo;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class Demo01ThreadAndHandlerUpdateUIActivity extends Activity {

	private Button btnGetImage = null;
	private ImageView imageViewer = null;
	private static final int MSG_SUCCESS = 0;
    private static final int MSG_FAILED= 1;

	private Handler  handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case MSG_SUCCESS:
				imageViewer.setImageBitmap((Bitmap)msg.obj);
				Toast.makeText(getApplication(), "Successfully!", 1000);
				break;
			case MSG_FAILED:
				Toast.makeText(getApplication(), "Failed!", 1000);
				break;
			}
		}
	};  
	
	private Runnable runnable = new Runnable() {
		public void run() {
			HttpClient hc = new DefaultHttpClient();  
            HttpGet hg = new HttpGet("http://avatar.csdn.net/0/3/4/1_mylzc.jpg");
            final Bitmap bm;  
            try {  
                HttpResponse hr = hc.execute(hg);  
                bm = BitmapFactory.decodeStream(hr.getEntity().getContent()); 
            } catch (Exception e) {  
                handler.obtainMessage(MSG_FAILED).sendToTarget();
                return;  
            }  
            // ���߳��й���һ��Message����ʹ��sendToTarget()��Message�����͵���Ϣ���С�
            handler.obtainMessage(MSG_SUCCESS,bm).sendToTarget();
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.demo01_thread_and_handler);
		
		btnGetImage = (Button)this.findViewById(R.id.btnGetImage);
		imageViewer = (ImageView)this.findViewById(R.id.imageViewer);

		btnGetImage.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// Ϊ�˷�ֹUI�߳���������һ���µ��̡߳�
				Thread thread = new Thread(runnable);
				thread.start();
			}
		});	
	}
}

